package org.jeecgframework.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mybatis.ext.WiseCoreService;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.ZyCinemaServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyEquipmentSpareServiceI;
import org.jeecgframework.web.service.ZyFileLogServiceI;
import org.jeecgframework.web.system.pojo.base.ZyCinemaEntity;
import org.jeecgframework.web.system.pojo.base.ZyCinemaHisEntity;
import org.jeecgframework.web.system.pojo.base.ZyFileLogEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author ZhangYunlong
 * @version V1.0
 * @Title: Controller
 * @Description: 影院
 * @date 2016-03-29 11:12:07
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyCinemaController")
public class ZyCinemaController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(ZyCinemaController.class); // NOPMD by dzqThinkpad on 16-4-1 下午3:01

    @Autowired
    private ZyCinemaServiceI zyCinemaService;
    @Autowired
    private ZyCommonService zyCommonService;

    @Autowired
    private SystemService systemService;
    private String message;

    @Autowired
    private WiseCoreService wiseCoreService;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 影院列表 页面跳转
     */
    @RequestMapping(params = "zyCinema")
    public ModelAndView zyCinema(HttpServletRequest request) {
        return new ModelAndView("com/zybk/zy_cinema/zyCinemaList");
    }


    /**
     * @author xiul
     * 2016-7-1 下午2:50:21
     * Description 影院列表页 datagrid
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(ZyCinemaEntity zyCinema, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();
        // Add start 没有检索条件时不检索内容 Amy 2018/3/9
        boolean flag = false;
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            if (key.equals("name") || key.equals("shortname") || key.equals("territoryName")
                    || key.equals("territoryName.TSTerritory.territoryName") || key.equals("isService") || key.equals("hasAuthUser") || key.equals("rectification")) {
                if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                    flag = true;//页面 查询条件为空不做查询
                    break;
                }
            }
        }
        // Add end 没有检索条件时不检索内容 Amy 2018/3/9
        if (flag) {
            for (Object key : request.getParameterMap().keySet()) {
                if ((String[]) request.getParameterMap().get(key) != null) {
                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                        }
                    }
                }
            }

            String parentTerritoryName = oConvertUtils.getString(request.getParameter("territoryName.TSTerritory.territoryName"));
            if (!StringUtil.isEmpty(parentTerritoryName)) {
                param.put("parentTerritoryName", parentTerritoryName);
            }
            //territoryName.TSTerritory.territoryName
            wiseCoreService.selectDataGrid("selectCinema", param, dataGrid);
        } else {
            dataGrid.setResults(new ArrayList<>());
        }
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * @author ZhangYunlong
     * @date 2016-3-28 下午5:57:10
     * @Description 影院列表 页面跳转从首页快速查询跳转过来
     */
    @RequestMapping(params = "homePageZyCinema")
    public ModelAndView homePageZyCinema(HttpServletRequest req) {
        req.setAttribute("name", oConvertUtils.getString(req.getParameter("name")));
        return new ModelAndView("com/zybk/zy_cinema/zyCinemaList");
    }


    /**
     * @author xiul
     * 2016-3-28 下午5:58:24
     * Description 弹出式影院选择页
     */
    @RequestMapping(params = "zyCinemas")
    public ModelAndView zyCinemas(HttpServletRequest request) {
        return new ModelAndView("com/zybk/zy_cinema/zyChooseCinemas");
    }

    /**
     * @author xiul
     * 2016-4-21 下午4:39:29
     * Description 弹出式影院选择页 datagrid
     */
    @RequestMapping(params = "datagridOfChooseCinema")
    public void datagridOfChooseCinema(ZyCinemaEntity zyCinema, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(ZyCinemaEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyCinema, request.getParameterMap());
        cq.add(Restrictions.or(Restrictions.eq("isDelete", "0"), Restrictions.isNull("isDelete")));//基本过滤条件，只查询未删除的数据
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.zyCinemaService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * @author xiul
     * 2016-3-28 下午5:58:24
     * Description 弹出式影院选择页 - 影厅页用
     */
    @RequestMapping(params = "zyChooseCinemaOfRoom")
    public ModelAndView zyChooseCinemaOfRoom(HttpServletRequest request) {
        return new ModelAndView("com/zybk/zy_cinema/zyChooseCinemaOfRoom");
    }

    /**
     * @author xiul
     * 2016-4-21 下午4:39:29
     * Description 弹出式影院选择页 datagrid - 影厅页用
     */
    @RequestMapping(params = "datagridOfzyChooseCinemaOfRoom")
    public void datagridOfzyChooseCinemaOfRoom(ZyCinemaEntity zyCinema, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(ZyCinemaEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyCinema, request.getParameterMap());
        cq.add(Restrictions.or(Restrictions.eq("isDelete", "0"), Restrictions.isNull("isDelete")));//基本过滤条件，只查询未删除的数据
        try {
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.zyCinemaService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * @author xiul
     * 2016-5-20 下午2:29:00
     * Description 弹出式影院选择页 - 设备添加， 修改页
     */
    @RequestMapping(params = "zyChooseCinemasForEs")
    public ModelAndView zyChooseCinemasForEs(HttpServletRequest request) {
        return new ModelAndView("com/zybk/zy_cinema/zyChooseCinemasOfEs");
    }

    /**
     * @author xiul
     * 2016-5-20 下午2:29:00
     * Description弹出式影院选择页 - 设备添加， 修改页 datagrid
     */
    @RequestMapping(params = "datagridOfChooseCinemaForEs")
    public void datagridOfChooseCinemaForEs(ZyCinemaEntity zyCinema, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(ZyCinemaEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyCinema, request.getParameterMap());
        cq.add(Restrictions.or(Restrictions.eq("isDelete", "0"), Restrictions.isNull("isDelete")));//基本过滤条件，只查询未删除的数据
        try {
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.zyCinemaService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * @author xiul
     * 2016-3-28 下午5:58:24
     * Description 弹出式影院选择页 - 联系人用
     */
    @RequestMapping(params = "zyChooseCmOfContact")
    public ModelAndView zyChooseCmOfContact(HttpServletRequest request) {
        return new ModelAndView("com/zybk/zy_cinema/zyChooseCmOfContact");
    }

    /**
     * @author xiul
     * 2016-4-21 下午4:39:29
     * Description 弹出式影院选择页 datagrid - 联系人用
     */
    @RequestMapping(params = "datagridOfChooseCmOfContact")
    public void datagridOfChooseCmOfContact(ZyCinemaEntity zyCinema, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(ZyCinemaEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyCinema, request.getParameterMap());
        cq.add(Restrictions.or(Restrictions.eq("isDelete", "0"), Restrictions.isNull("isDelete")));//基本过滤条件，只查询未删除的数据
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.zyCinemaService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * @Description 逻辑删除影院
     * @author ZhangYunlong
     * @date 2016-3-28 下午5:57:10
     */
    @RequestMapping(params = "dologicDel")
    @ResponseBody
    public AjaxJson dologicDel(ZyCinemaEntity zyCinema, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        zyCinema = systemService.getEntity(ZyCinemaEntity.class, zyCinema.getId());
        message = "影院[" + zyCinema.getName() + "]删除成功";
        try {
            zyCinema.setIsDelete("1");
            zyCinemaService.saveOrUpdate(zyCinema);
            ZyCinemaHisEntity zyCinemaHis = new ZyCinemaHisEntity();
            MyBeanUtils.copyBeanNotNull2Bean(zyCinema, zyCinemaHis);
            zyCinemaHis.setDataStatus("delete");
            zyCinemaHis.setBusId(zyCinema.getId());
            zyCinemaService.save(zyCinemaHis);
        } catch (Exception e) {
            e.printStackTrace();
            message = "影院[" + zyCinema.getName() + "]删除失败";
        }
        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        j.setMsg(message);
        return j;
    }

    /**
     * @Description 添加影院
     * @author ZhangYunlong
     * @date 2016-3-28 下午5:57:10
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(ZyCinemaEntity zyCinema, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "影院[" + zyCinema.getName() + "]添加成功";
        if (zyCinema.getProvince().getId().equals("")) {
            zyCinema.setProvince(null);
        }
        if (zyCinema.getBelongOrg().getId().equals("")) {
            zyCinema.setBelongOrg(null);
        }
        try {
            zyCinema.setIsDelete("0");
            zyCinemaService.save(zyCinema);
            ZyCinemaHisEntity zyCinemaHis = new ZyCinemaHisEntity();
            MyBeanUtils.copyBeanNotNull2Bean(zyCinema, zyCinemaHis);
            zyCinemaHis.setBusId(zyCinema.getId());
            zyCinemaHis.setDataStatus("create");
            zyCinemaService.save(zyCinemaHis);
        } catch (Exception e) {
            e.printStackTrace();
            message = "影院[" + zyCinema.getName() + "]添加失败";
            throw new BusinessException(e.getMessage());
        }
        systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        j.setMsg(message);
        return j;
    }

    /**
     * @Description 更新影院
     * @author ZhangYunlong
     * @date 2016-3-28 下午5:57:10
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(ZyCinemaEntity zyCinema, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        ZyCinemaEntity t = zyCinemaService.get(ZyCinemaEntity.class, zyCinema.getId());
        String name = t.getName();
        message = "影院[" + name + "]更新成功";
        if (null != zyCinema.getProvince() && zyCinema.getProvince().getId().equals("")) {
            zyCinema.setProvince(null);
        }
        if (null != zyCinema.getBelongOrg() && zyCinema.getBelongOrg().getId().equals("")) {
            zyCinema.setBelongOrg(null);
        }
        try {
            MyBeanUtils.copyBean2Bean(t, zyCinema);
            systemService.saveOrUpdate(t);
            ZyCinemaHisEntity zyCinemaHis = new ZyCinemaHisEntity();
            MyBeanUtils.copyBeanNotNull2Bean(t, zyCinemaHis);
            zyCinemaHis.setDataStatus("update");
            zyCinemaHis.setBusId(t.getId());
            systemService.save(zyCinemaHis);
            /** update by xiu 160722 由于 去掉了设备的所属省市, 所以此处在更新影院时 更新其下的所有设备的省市字段 */
            zyCinemaService.updateEsOfCm(t);
        } catch (Exception e) {
            e.printStackTrace();
            message = "影院[" + name + "]更新失败";
        }
        systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        j.setMsg(message);
        return j;
    }


    /**
     * 影院新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(ZyCinemaEntity zyCinema, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(zyCinema.getId())) {
            zyCinema = zyCinemaService.getEntity(ZyCinemaEntity.class, zyCinema.getId());
            req.setAttribute("zyCinemaPage", zyCinema);
        }
        return new ModelAndView("com/zybk/zy_cinema/zyCinema-add");
    }

    /**
     * 影院编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(ZyCinemaEntity zyCinema, HttpServletRequest req) {
        List list = new ArrayList();
        Map map = new HashMap();
        if (StringUtil.isNotEmpty(zyCinema.getId())) {
            zyCinema = zyCinemaService.getEntity(ZyCinemaEntity.class, zyCinema.getId());
            List<ZyFileLogEntity> zyFileLogEntityList = systemService.findByProperty(ZyFileLogEntity.class, "businessKey", zyCinema.getId());
            req.setAttribute("zyCinemaPage", zyCinema);
            if (zyFileLogEntityList.size() > 0) {
                for (ZyFileLogEntity zyFileLogEntity : zyFileLogEntityList) {
                    map.put("name", zyFileLogEntity.getOldFileName());
                    map.put("id", zyFileLogEntity.getId());
                    list.add(map);
                }
            }
            req.setAttribute("list", list);
        }
        return new ModelAndView("com/zybk/zy_cinema/zyCinema-update");
    }

    /**
     * @param param validataForm ajaxUrl 参数
     * @author xiul
     * 2016-6-16 下午3:30:22
     * Description 检查影院中文名唯一性
     */
    @ResponseBody
    @RequestMapping(params = "checkCinemaNameUnique")
    public ValidForm checkCinemaNameUnique(@RequestParam(value = "param", defaultValue = "") String param,
                                           @RequestParam(value = "cinemaId", defaultValue = "") String cinemaId
    ) {
        ValidForm vf = new ValidForm();
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT COUNT(1) AS total ");
        sql.append(" FROM zy_cinema cm");
        sql.append(" WHERE ");
        sql.append(" cm.name = '" + param + "' ");
        sql.append(" AND cm.is_delete = 0 ");
        if (StringUtil.isNotEmpty(cinemaId)) {
            sql.append(" AND id != '" + cinemaId + "' ");
        }
        int total = zyCommonService.getCountBySql(sql.toString());
        if (total > 0) {
            vf.setStatus(ValidForm.N);
            vf.setInfo("当前影院中文名已经存在");
        }
        return vf;
    }

    /**
     * 影院查看页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goView")
    public ModelAndView goView(ZyCinemaEntity zyCinema, HttpServletRequest req) {
        List list = new ArrayList();
        Map map = new HashMap();
        if (StringUtil.isNotEmpty(zyCinema.getId())) {
            zyCinema = zyCinemaService.getEntity(ZyCinemaEntity.class, zyCinema.getId());
            req.setAttribute("zyCinemaPage", zyCinema);
            List<ZyFileLogEntity> zyFileLogEntityList = systemService.findByProperty(ZyFileLogEntity.class, "businessKey", zyCinema.getId());
            if (zyFileLogEntityList.size() > 0) {
                for (ZyFileLogEntity zyFileLogEntity : zyFileLogEntityList) {
                    map.put("name", zyFileLogEntity.getOldFileName());
                    map.put("id", zyFileLogEntity.getId());
                    list.add(map);
                }
            }
            req.setAttribute("list", list);
        }
        return new ModelAndView("com/zybk/zy_cinema/zyCinema-view");
    }

    /**
     * 影院查看页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goViews")
    public ModelAndView goViews(HttpServletRequest req) {
        String id = req.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            ZyCinemaEntity zyCinema = zyCinemaService.getEntity(ZyCinemaEntity.class, id);
            req.setAttribute("zyCinemaPage", zyCinema);
        }
        return new ModelAndView("com/zybk/zy_cinema/zyCinema-view");
    }
}
